<?php
require_once "../common/common.php";
require_once MODEL."/user.php";

if (isset($_SESSION['user'])) {
    header("Location:./we_bug_env.php");
} else{
    
    if (isset($_REQUEST['submit'])) {
        $name = [
            'username' => '用户名',
            'password' => '密码',
            'repassword' => '确认密码',
            'qq' => 'QQ号',
            'captcha' => '图形验证码'
        ];
        foreach ($name as $k => $n) {
            $val = $_REQUEST[$k];
            if (empty($val)) {
                echo '<script>alert("请输入' . $n . '");history.go(-1);</script>';
                exit;
            }
        }

        //图形验证码
        if ($_SESSION['captch'] != $_REQUEST['captcha']) {
            echo '<script>alert("图形验证码错误");history.go(-1);</script>';
            exit;
        }
        //用户名
        $len = strlen($_REQUEST['username']);
        if ($len > 20 || $len < 6) {
            echo '<script>alert("用户名长度为6-20位");history.go(-1);</script>';
            exit;
        }
        if (preg_match('/[^A-Za-z0-9_]/', $_REQUEST['username'])) {
            echo '<script>alert("用户名只能由数字、字母、下划线组成");history.go(-1);</script>';
            exit;
        }
        //密码
        $len = strlen($_REQUEST['password']);
        if ($len > 30 || $len < 8) {
            echo '<script>alert("密码长度为8-30位");history.go(-1);</script>';
            exit;
        }
        if (preg_match('/[^A-Za-z0-9_]/', $_REQUEST['password'])) {
            echo '<script>alert("密码只能由数字、字母、下划线组成");history.go(-1);</script>';
            exit;
        }
        //确认密码
        if ($_REQUEST['password'] != $_REQUEST['repassword']) {
            echo '<script>alert("确认密码与密码不一致");history.go(-1);</script>';
            exit;
        }
        //qq
        if (!preg_match('/[1-9][0-9]{4,14}/', $_REQUEST['qq'])) {
            echo '<script>alert("请输入有效的QQ号");history.go(-1);</script>';
            exit;
        }

        $sql = "SELECT id FROM user WHERE username = ? or qq = ?";
        $stmt = $sysConnect->prepare($sql);
        $stmt->bind_param("ss", $_REQUEST['username'], $_REQUEST['qq']);
        $result = $stmt->bind_result($id);
        $stmt->execute();
        while ($stmt->fetch()) {
            echo '<script>alert("用户名或QQ号已经存在");history.go(-1);</script>';
            exit;
        }
        $sql = "insert into user (username,password,nickname,credit,qq) values (?,?,?,0,?)";
        $stmt = $sysConnect->prepare($sql);
        $stmt->bind_param("ssss", $v1, $v2, $v1, $v3);
        $v1 = $_REQUEST['username'];
        $v2 = $_REQUEST['password'];
        $v3 = $_REQUEST['qq'];
        $stmt->execute();

        echo '<script>alert("注册成功，请前往登录");location.href="/control/login.php";</script>';
        exit;
    }
    
    require_once TPMELATE."/register.php";
}